package org.suyafei.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.suyafei.config.SmsConfig;

/**
 * @author 宿某人
 * @Date: 2021/12/06/11:32 下午
 * @Description:
 */
@Component
@Slf4j
public class SmsComponent {
    /**
     *发送地址
     */
    private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    @Async("threadPoolTaskExecutor")
    public void send(String to, String templateId, String value) {
        String url = String.format(URL_TEMPLATE, to, templateId, value);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.set("Authorization", "APPCODE " + smsConfig.getAppCode());

        HttpEntity entity = new HttpEntity(httpHeaders);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        log.info("url={},body{}", url, response.getBody());

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("发送短信验证码成功");
        }else {
            log.error("发送短信验证码失败：{}"+response.getBody());
        }
    }


}
